<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-回花称重`"
		width="960px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:show-confirm-btn="pageType !== 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail' || ruleForm.auditState === 1" label-width="110px" :show-message="false">
			<div ref="box1">
				<div class="flex-start-center margin-bottom-4" style="font-size: 13px;">
					<el-tag v-if="!ruleForm.code" type="primary" effect="plain" class="">
						<span class="el-icon-tickets item-gap"></span>
						<span>基本信息</span>
					</el-tag>
					<div v-else style="font-size: 16px;">
						<span class="el-icon-star-off item-gap"></span>
						<span>{{ ruleForm.code || '系统自动生成' }}</span>
					</div>
				</div>
				<jk-card>
					<el-row class="flex-start-center-wrap">
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="日期">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.belongDate }}</span>
								<jk-date-picker v-else v-model="ruleForm.belongDate" size="medium" placeholder="" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="班次">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.shiftName }}</span>
								<jk-select v-else v-model="ruleForm.shiftName" class="width-100-percent" :option-list="shiftList" size="medium" placeholder="" @change="onScheduleShiftChange" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="送料人" prop="giveEmpName">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.giveEmpName }}</span>
								<remote-search-semp-input
									v-else
									placeholder="送料人"
									only-key="giveEmpId"
									query-name="giveEmpName"
									:form-data="ruleForm"
									@on-select="onSelectGiveEmpChange"
								></remote-search-semp-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="收料人" prop="takeEmpName">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.takeEmpName }}</span>
								<remote-search-emp-input
									v-else
									placeholder="收料人"
									only-key="takeEmpId"
									query-name="takeEmpName"
									:form-data="ruleForm"
									@on-select="onSelectTakeEmpChange"
								></remote-search-emp-input>
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
				<el-button class="margin-bottom-4 margin-top-10" icon="el-icon-plus" :disabled="pageType === 'detail'" size="mini" type="primary" @click="onAddBtn">添加</el-button>
			</div>
			<jk-table
				ref="jkTable"
				border
				show-footer
				:footer-method="footerMethod"
				:data="ruleForm.itemList"
				:height="dialogTableHeight - 20"
			>
				<vxe-column title="操作" align="center" field="operation" :width="70">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button size="mini" icon="el-icon-minus" :disabled="pageType === 'detail'" @click="ruleForm.itemList.splice(scope.rowIndex, 1)" />
						</div>
					</template>
				</vxe-column>
				<vxe-column title="回花种类" align="left" field="unitPrice" :min-width="100">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1">{{ scope.row.materialName }}</span>
						<el-select v-else v-model="scope.row.materialId" size="mini" placeholder="请选择" class="width-100-percent" @change="onLapWasteVarietyChange($event, scope.rowIndex)">
							<el-option v-for="item in lapWasteVarietyList" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</template>
				</vxe-column>
				<vxe-column title="包数" align="right" field="packNum" :min-width="120">
					<template slot-scope="scope">
						<span>{{ scope.row.packNum }}</span>
					</template>
				</vxe-column>
				<vxe-column title="重量(公斤)" align="right" field="totalWeight" :width="100">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1">{{ scope.row.totalWeight }}</span>
						<jk-number-input v-else v-model="scope.row.totalWeight" size="mini" placeholder="" @change="updateFooterEvent" />
					</template>
				</vxe-column>
			</jk-table>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import remoteSearchProductInput from '../../technology/order/components/remote-search-product-input';
    import { formatDate, formatTime } from '../../../utils/jk/jk-tool';
    import { workforceManagementShiftGetByTime, workforcemanagementShiftPage } from '@/api/schedule/shift';
    import { spinMaterialPage } from '@/api/material/rawMaterial';
    import {
        productionMaterialWeighCreate,
        productionMaterialWeighGet,
        productionMaterialWeighUpdate
    } from '@/api/material/huiHuaWeighing';
    import remoteSearchEmpInput from './remote-search-emp-input/index.vue';
    import remoteSearchSempInput from './remote-search-semp-input/index.vue';
    import XEUtils from 'xe-utils';
    export default {
        mixins: [calHeight],
        components: { remoteSearchEmpInput, remoteSearchProductInput, remoteSearchSempInput },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                tableLoading: false,
                saveBtnLoading: false,
                shiftList: [],
                workshopList: [],
                lapWasteVarietyList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    'auditState': null,
                    'remark': '',
                    'typeCode': 'HH',
                    'typeId': 142,
                    'typeName': '回花',
                    'itemList': [
                        { packNum: 1 }, { packNum: 1 }, { packNum: 1 }, { packNum: 1 }, { packNum: 1 }, { packNum: 1 }, { packNum: 1 }, { packNum: 1 }
                    ]
                },
                rules: {
                    giveEmpName: [{ required: true, trigger: 'change' }],
                    takeEmpName: [{ required: true, trigger: 'change' }]
                },
                defaultRowData: {
                    packNum: 1
                }
            };
        },
        methods: {
            updateFooterEvent() {
                const $table = this.$refs.jkTable.$refs.xTable;
                $table.updateFooter();
            },
            onAddBtn() {
                this.ruleForm.itemList.push(JSON.parse(JSON.stringify(this.defaultRowData)));
            },
            footerMethod({ columns, data }) {
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return '合计';
                        }
                        if (columnIndex === 2) {
                            return `${this.sumNum(data, 'packNum')}`;
                        }
                        if (columnIndex === 3) {
                            return `${this.sumNum(data, 'totalWeight') ? this.sumNum(data, 'totalWeight') : ''}`;
                        }
                        return '';
                    })
                ];
            },
            sumNum(list, field) {
                let count = 0;
                list.forEach(item => {
                    count += Number(item[field]);
                });
                return count;
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) {
                    params.auditState = 1;
                    delete params.id;
                }
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    this.sweepAwayEmptyList();
                    const materialId = this.ruleForm.itemList.every(x => x.materialId);
                    if (valid && materialId) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            // 去除未填写的列表
            sweepAwayEmptyList() {
                const tempList = this.ruleForm.itemList.filter(x =>
                    x.materialId ||
                    x.packWeight ||
                    x.totalWeight
                );
                this.ruleForm.itemList = tempList;
            },
            onSelectGiveEmpChange(e) {
                let item = {};
                if (e) {
                    item = {
                        id: e.id
                    };
                } else {
                    item = {};
                }
                this.$set(this.ruleForm, 'giveEmpId', e.id);
                this.$set(this.ruleForm, 'giveEmpName', e.name);
                this.$set(this.ruleForm, 'giveEmpCode', e.code);
            },
            onSelectTakeEmpChange(e) {
                let item = {};
                if (e) {
                    item = {
                        id: e.id
                    };
                } else {
                    item = {};
                }
                this.$set(this.ruleForm, 'takeEmpId', e.id);
                this.$set(this.ruleForm, 'takeEmpName', e.name);
                this.$set(this.ruleForm, 'takeEmpCode', e.code);
            },
            onLapWasteVarietyChange(item, index) {
                this.lapWasteVarietyList.forEach(x => {
                    if (item === x.id) {
                        this.$set(this.ruleForm.itemList[index], 'materialCode', x.code);
                        this.$set(this.ruleForm.itemList[index], 'materialName', x.name);
                    }
                });
            },
            getLapWasteVariety() {
                const params = {
                    pageNo: 1,
                    pageSize: 100,
                    typeCode: 'HH'
                };
                return spinMaterialPage(params).then(res => {
                    if (res.data.status === 200) {
                        this.lapWasteVarietyList = res.data.res;
                    }
                });
            },
            createAndUpdateRequest() {
                const api = !this.dataId ? productionMaterialWeighCreate : productionMaterialWeighUpdate;
                this.saveBtnLoading = true;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return productionMaterialWeighGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                    }
                });
            },
            onScheduleShiftChange(e) {
                let item = {};
                if (e) {
                    item = this.shiftList.find(x => x.id === e);
                } else {
                    item = {
                        id: null,
                        shiftId: null,
                        shiftName: null
                    };
                }
                this.$set(this.ruleForm, 'shiftId', item.id);
                this.$set(this.ruleForm, 'shiftName', item.name);
            },
            // 当前班次信息
            getScheduleShift() {
                const params = {
                    workshopId: this.ruleForm.workshopId,
                    belongTime: formatTime(Date.now())
                };
                return workforceManagementShiftGetByTime(params).then(res => {
                    if (res.data.status === 200) {
                        this.$set(this.ruleForm, 'shiftName', res.data.res.currentShiftInfo.name);
                        this.$set(this.ruleForm, 'shiftId', res.data.res.currentShiftInfo.id);
                        this.$set(this.ruleForm, 'shiftCode', res.data.res.currentShiftInfo.code);
                    }
                });
            },
            // 获取区域的班次
            getShiftListByWorkshopRequest() {
                this.shiftList = [];
                if (!this.ruleForm.workshopId) return;
                return workforcemanagementShiftPage({
                    workshopId: this.ruleForm.workshopId
                }).then(res => {
                    if (res.data.status === 200) {
                        this.shiftList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList.find(x => x.code === 'QF');
                this.$set(this.ruleForm, 'workshopId', this.workshopList.id);
                this.$set(this.ruleForm, 'workshopCode', this.workshopList.code);
                this.$set(this.ruleForm, 'workshopName', this.workshopList.name);
                await this.getShiftListByWorkshopRequest();
                await this.getScheduleShift();
                await this.getLapWasteVariety();
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'workshopId', this.$route.query.workshopId ? Number(this.$route.query.workshopId) : this.$store.state.user.userWorkshop.defaultWorkshopId);
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                }
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
